package com.dy.队列.链队列;

import com.dy.线性表.链表.Node;
import com.dy.队列.IQueue;

public class LinkQueue implements IQueue {
    public static void main(String[] args) throws Exception {
        LinkQueue lq = new LinkQueue();
        lq.offer(1);
        lq.offer(2);
        System.out.println(lq.poll());
        System.out.println(lq.poll());
    }

    private Node front, rear;

    @Override
    public void clear() {
        front = null;
        rear = null;
    }

    @Override
    public boolean isEmpty() {
        return front == null;
    }

    @Override
    public int length() {
        Node tmp = front;
        int len = 0;
        while (tmp != null) {
            len++;
            tmp = tmp.next;
        }
        return len;
    }

    @Override
    public Object peek() {
        if (front != null) {
            return front.data;
        } else return null;
    }

    @Override
    public void offer(Object x) throws Exception {
        Node newNode = new Node(x);
        if (front != null) {//非空
            rear.next = newNode;
            rear = newNode;
        } else {
            front = rear = newNode;
        }
    }

    @Override
    //出队
    public Object poll() {
        if (front == null) {
            return null;
        } else {
            Object t = front.data;
            Node tmp = front;
            front = front.next;
            if(tmp==rear){
                rear=null;//出队尾，说明只有一个元素
            }

            return t;
        }
    }
}
